package cn.javaxc.mvcwork.action;

import java.io.*;
import java.net.SocketException;
import java.sql.*;
import java.util.*;
import javax.servlet.http.*;
import org.springframework.web.servlet.ModelAndView;


import cn.javaxc.mvcwork.controller.*;
import cn.javaxc.mvcwork.controller.web.*;
import cn.javaxc.mvcwork.framework.actions.TActionContext;
import cn.javaxc.model.page.*;
import cn.javaxc.mvcwork.modules.file.*;
import cn.javaxc.mvcwork.util.helper.*;
import cn.javaxc.mvcwork.util.common.*;
import cn.javaxc.mvcwork.controller.AppUtils;
import cn.javaxc.mvcwork.framework.actions.*;
import cn.javaxc.mvcwork.modules.login.UserBean;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.beans.factory.annotation.Autowired;
import cn.javaxc.mvcwork.util.helper.IBaseDAO;

public class MVCAction extends TModuleAction 
//,com.opensymphony.xwork2.interceptor.NoParameters
{
  @Autowired
  protected IBaseDAO dao;
	public String getPage(){
	 String includePage = (String)context.getAttribute("include");
	 if (includePage==null){
		String action = context.getRequest().getServletPath();
		action=action.substring(1);
		if (action.indexOf("/")>0){
			includePage=action.substring(action.indexOf("/"));
			if (includePage.endsWith(".do")){
				includePage=includePage.substring(0,includePage.length()-".do".length());
			}
//			if (includePage.contains("!")){
				String event=includePage.substring(includePage.lastIndexOf("/")+1);
				context.setAttribute("include.event",event);
				includePage=includePage.substring(0,includePage.lastIndexOf("/"));
//			}
			context.setAttribute("include",includePage);
		}
	 }
	 return includePage;
	}
	protected VUEPage createPage() throws Exception{
//		return MVCProcess.createPage(context);
	 String includePage = getPage();
	  return createPage(includePage);
	}
	protected VUEPage submitPage() throws Exception{
//		return MVCProcess.submitPage(context);
		return createPage();
	}

    protected VUEPage createPage(String clazz) throws Exception{
		return staticPage(clazz);
    }
    public static VUEPage staticPage(String clazz) throws Exception{
		if (clazz.startsWith("/")){
			clazz=clazz.substring(1);
		}
		VUEPage page=(VUEPage)Class.forName("cn.javaxc."+clazz.replaceFirst("/","/action/").replace("/",".")).newInstance();
		SpringUtils.getApplicationContext().getAutowireCapableBeanFactory().autowireBean(page);
		return page;
    }
  protected boolean processValidate() throws Exception {
	if (!super.processValidate())return false;
	if (context.getFormBean() instanceof VUEFormBean){
		VUEFormBean emtMap=(VUEFormBean)context.getFormBean();
		if (emtMap.getErrList().size()>0){

			return false;
		}
	}
	
    return true;
  }
  protected boolean doError(Object result) {
	return result==null||!"true".equals(context.getAttribute("ttpselferror"));
  }
  protected void setActionPath(Object page,String s){
	  context.setAttribute("mvc_page_id",page.getClass().getName());
	  if (page!=null&&context.getAttribute("__action_path__")==null){
		context.setAttribute("__action_path__","/"+page.getClass().getName().replace(".","/")+"!"+s+".mvc");	
	  }
  }
  protected String doPermission()throws Exception{

	String ret=super.doPermission();
	if (ret!=null)return ret;

	  AppUtils.addFormElements(context);
	boolean hasPermission=true;


//    try {
	  PagedListInfo searchListInfo = this.getPagedListInfo(MVCConstant.mvc_page_list);
	 VUEPage page=createPage();
	 
//	  page.setConnection( db);
      page.setContext( context);
	  
	  page.setPagination( searchListInfo);
	  page.onhead();
	  page.hasPermission();
	  hasPermission=page.getHasPermission();
	  
//    } catch (Exception e) {
//		
//      context.setError( e);
//      if(doError(null))return (SystemError);
//    }
	if (!hasPermission){
		return PermissionError;
	}
	return null;
  }
//  public String getTemplate(String include){
//	return null;
//  }

  public Object executeIndex() throws Exception{



	Object result="Include";
	VUEPage page=null;
//    try {
	   PagedListInfo searchListInfo = this.getPagedListInfo(MVCConstant.mvc_page_list);
	   if(!"true".equals(context.getParameter("ttppage"))){
			searchListInfo.setCurrentOffset(0);
//			searchListInfo.setColumnToSortBy(null);
//			searchListInfo.setSortOrder("");
//			searchListInfo.setItemsPerPage(PagedListInfo.DEFAULT_ITEMS_PER_PAGE);
		}
	  //getAttribute去submit错误页
	 page=createPage();
	 setActionPath(page,"onload");
	 
      page.setContext( context);
//	  page.beginTransaction(false);
	  
	  page.setPagination( searchListInfo);
		page.onhead();
		page.onloadsubmit();
		result=page.onload();
		if ("true".equals(context.getConfig().get("layout.pagetext","false"))){
			context.setAttribute("__mvctext__",dao.getpagetext(page.getClass().getName()));
		}
	    AppUtils.addFormElements(context);
	  MVCConfig.getRequestHelper().createTParams(context.getRequest());
//    } catch (Exception e) {
//		
//      context.setError( e);
//      if(doError(result))return (SystemError);
//    }
//	finally {
//      if (page != null) {
//			page.endTransaction(false);
//		}
//    }
    return getReturn (result);
	
  }




 public Object executeLoadEvent() throws Exception{

    AppUtils.addFormElements(context);
	VUEPage page=null;
	 Object result="Include";
//    try {
	  PagedListInfo searchListInfo = this.getPagedListInfo( MVCConstant.mvc_page_list);
	   if("true".equals(context.getParameter("initMenu"))){
			searchListInfo.setCurrentOffset(0);
			searchListInfo.getMap().clear();
//			searchListInfo.setColumnToSortBy(null);
//			searchListInfo.setSortOrder("");
//			searchListInfo.setItemsPerPage(PagedListInfo.DEFAULT_ITEMS_PER_PAGE);
		}
	page=createPage();
	setActionPath(page,context.getParameter("event"));
	
	  page.setPagination( searchListInfo);
      page.setContext( context);
	  	  
//	  page.beginTransaction(false);
	  page.onhead();
	  String event=(String)context.getAttribute("include.event");
	  context.getRequest().removeAttribute("include.event");
	  result=ObjectHelper.invokeObjectEx(page,event,new Object[0],new Class[0]);
//    } catch (Exception e) {
//		
//      context.setError( e);
//      if(doError(result))return (SystemError);
//    } 
//	finally {
//      if (page != null) {
//			page.endTransaction(false);
//		}
//    }
    return getReturn (result);
	
  }
  public Object executeSubmit() throws Exception{

    AppUtils.addFormElements(context);


	VUEPage page=null;
	Object result="Submit";
    try {
		PagedListInfo searchListInfo = this.getPagedListInfo( MVCConstant.mvc_page_list);
	  page=submitPage();
	  setActionPath(page,"onsubmit");
      page.setContext( context);
	  
	 
//	  page.beginTransaction(true);
		page.setPagination( searchListInfo);
		context.getRequest().removeAttribute("include.event");
		page.onvalidate();
		if (!processValidate()){
			return doReturn (result);
		}
		result=page.onsubmit();
		
		if (!processValidate()){
//			page.rollback();
			return doReturn (result);
		}
//		page.commit();
	  
		AppUtils.setSourcePage(context); 
    } catch (Exception e) {
		
//	  if (page != null) {
//		  page.rollback();	
//	  }
	  if(MVCConfig.getConfig().isRollbackOnly())TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      context.setError( e);
      if(doError(result))return (SystemError);

    } 
//	finally {
//		if (page != null) {
//			page.endTransaction(true);
//		}
//    }
	String cpopup = context.getParameter("cpopup");
	boolean new_popup_submit = "true".equals(context.getParameter("new_popup_submit"));
    if (!new_popup_submit&&cpopup!=null&&!cpopup.equals("")) {
      return doReturn ("CPopup");
    }
	return doReturn (result);
	
  }
 public Object executeExecEvent() throws Exception{
    AppUtils.addFormElements(context);
	VUEPage page=null;

	Object result="Submit";
    try {
	  PagedListInfo searchListInfo = this.getPagedListInfo( MVCConstant.mvc_page_list);


	  page=submitPage();
	  setActionPath(page,context.getParameter("event"));
	  
      page.setContext( context);
//	  page.beginTransaction(true);
	  page.setPagination( searchListInfo);
	  String event=(String)context.getAttribute("include.event");
	  context.getRequest().removeAttribute("include.event");
	  result=ObjectHelper.invokeObjectEx(page,event,new Object[0],new Class[0]);
	  if (!processValidate()){

	  }
//	  page.commit();
	  AppUtils.setSourcePage(context); 
    } catch (Exception e) {
		
//		if (page != null) {
//		  page.rollback();	
//	  }
	  if(MVCConfig.getConfig().isRollbackOnly())TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      context.setError( e);
      if(doError(result))return (SystemError);
    } 
//	finally {
//		if (page != null) {
//			page.endTransaction(true);
//		}
//    }

	String cpopup = context.getParameter("cpopup");
	boolean new_popup_submit = "true".equals(context.getParameter("new_popup_submit"));
    if (!new_popup_submit&&cpopup!=null&&!cpopup.equals("")) {
      return getReturn ("CPopup");
    }
    return doReturn (result);
	
  }
  public String executeReturn() {
		String ret=context.getParameter("return");
		if (ret!=null){
			return ret;
		}
		return "DefaultOK";
  }
  public String executeFrame() {
		String query=context.getRequest().getQueryString();
		context.setAttribute("frame_url",context.getRequest().getRequestURL()+"?"+query.replace("execute=Frame",""));
		context.setAttribute("ttpdebug","false");
		return "treegrid_frameOK";
  }


	@Override
	protected String getCommand() {
		getPage();
		HttpServletRequest request = context.getRequest();
		String command = "Index";
		if (request.getQueryString() != null) {
		  if (request.getQueryString().indexOf("execute=") > -1) {
			command = request.getParameter("execute");
			if (command!=null){
				return command;
			}
		  }
		}
		Object event=context.getAttribute("include.event");
		if (event!=null){
			if ("onsubmit".equals(event)){
				return "Submit";
			}else if ("POST".equals(context.getRequest().getMethod())){
				return "ExecEvent";
			}else{
				return "LoadEvent";
			}
		}
		return command;
	}

	protected void populateBean(Object bean){
		HttpServletRequest request=context.getRequest();
		if (bean instanceof VUEFormBean){
			VUEFormBean emtMap=(VUEFormBean)bean;
			Enumeration<String> e = request.getParameterNames();
			while (e.hasMoreElements()){
				String param = e.nextElement();
				if (param.startsWith("element-")){
					String[] params=param.split("-");					
					if (params.length==2){
						String[] ps1=params[1].split("\\.");
						if (ps1.length>=2){
							if ("table".equals(ps1[1])){
								if (CommonUtil.parseInt(ps1[0],-1)>0){
									emtMap.getElement(CommonUtil.parseInt(ps1[0],-1)).setTable(request.getParameter(param));
								}
							}
						}
					}else if (params.length==3){
						String[] ps1=params[1].split("\\.");
						if (ps1.length>=2){
							if ("map".equals(ps1[1])){
								if (CommonUtil.parseInt(ps1[0],-1)>0){
									emtMap.getElement(CommonUtil.parseInt(ps1[0],-1)).put(params[2],request.getParameter(param));
								}
							}
						}
					}
				}
			}
		}
	}
}
